<template>
    <div class="user-data page-container">
        <el-row class="user-data_row user-data_row--filter" type="flex">
            <el-select class="filter-item" v-model="queryParameter.category" placeholder="品类" clearable>
                <el-option
                        v-for="{ value, label } in options.category"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.model" placeholder="型号" clearable>
                <el-option
                        v-for="{ value, label} in options.model"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.province"
                       placeholder="省"
                       @change="_getCityListByProvince" clearable>
                <el-option
                        v-for="{ value, label } in options.province"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
            <el-select class="filter-item" v-model="queryParameter.city" placeholder="市" clearable>
                <el-option
                        v-for="{ value, label } in options.city"
                        :key="value"
                        :label="label"
                        :value="value">
                </el-option>
            </el-select>
        </el-row>
        <el-row class="user-data_row user-data_row--filter" type="flex">
            <el-radio
                    class="filter-item"
                    v-for="{label, value} in dateOptions"
                    v-model="dateRange"
                    :key="value"
                    :label="value"
                    @change="handleDateChange"
                    border>
                {{label}}
            </el-radio>
            <el-date-picker
                    v-show="showDateRangePicker"
                    class="filter-item"
                    v-model="queryParameter.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd">
            </el-date-picker>
        </el-row>
        <el-row class="user-data_row user-data_row--survey">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">用户概览</span>
                    <el-radio-group v-if="false" class="radio_data-range mui-radio-group" size="mini"
                                    v-model="surveyDateRange">
                        <el-radio-button label="1">近1天</el-radio-button>
                        <el-radio-button label="7">近7天</el-radio-button>
                        <el-radio-button label="30">近30天</el-radio-button>
                    </el-radio-group>
                </el-row>
                <el-row type="flex" class="card-content" v-loading="loadingOverView">
                    <div class="data-item" v-for="{num, label, trend} in userSurveyData" :key="label">
                        <div class="item-row num">{{num | numCommaFormat}}</div>
                        <div class="item-row label">{{label}}</div>
                        <el-row type="flex" justify="space-between" class="item-row trend" v-if="trend">
                            <span>环比<span class="range">({{surveyDateRange}}天)</span></span>
                            <span>{{trend}}%</span>
                        </el-row>
                    </div>
                </el-row>
            </el-card>
        </el-row>
        <el-row class="user-data_row user-data_row--stage-trend">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">各阶段用户变化趋势</span>
                    <el-radio-group class="radio_data-type mui-radio-group" size="mini" v-model="userStageTrendCheckedType">
                        <el-radio-button label="day">日</el-radio-button>
                        <el-radio-button label="month">月</el-radio-button>
                    </el-radio-group>
                </el-row>
                <ChartStageTrend :query-data="queryParameter" :type="userStageTrendCheckedType" class="card-content chart-item"
                                 style="min-height: 24vh;"/>
            </el-card>
        </el-row>
        <el-row class="user-data_row user-data_row--distribution">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">地域分布</span>
                </el-row>
                <RegionDistribution :query-data="queryParameter" class="card-content"/>
            </el-card>
        </el-row>
        <el-row v-if="false" class="user-data_row user-data_row--ratio" type="flex">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">性别数量比列</span>
                </el-row>
                <GenderRatio :query-data="queryParameter" class="card-content"/>
            </el-card>
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">年龄数量比例</span>
                </el-row>
                <AgeRatio :query-data="queryParameter" class="card-content"/>
            </el-card>
        </el-row>
        <el-row v-if="false" class="user-data_row user-data_row--retention">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">新增用户留存分析</span>
                    <el-button-group class="index-btn-group">
                        <el-button class="label">指标</el-button>
                        <el-date-picker
                                class="filter-item"
                                v-model="retentionDateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </el-button-group>
                </el-row>
                <UserRetentionAnalysis :query-data="queryParameter" class="card-content"/>
            </el-card>
        </el-row>
        <el-row class="user-data_row user-data_row--active-period">
            <el-card class="box-card">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">活跃高峰时段</span>
                </el-row>
                <ActivePeriod :query-data="queryParameter" class="card-content" style="height: 28vh"/>
            </el-card>
        </el-row>
        <el-row class="user-data_row user-data_row--etc-Info" type="flex">
            <el-card class="box-card" style="flex: auto">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">口味偏好</span>
                    <el-link class="more">更多</el-link>
                </el-row>
                <TableSimple v-loading="loadingTableTasteHabit" class="card-content" :tableData="tasteHabitTable"
                             height="35vh"/>
            </el-card>
            <el-card class="box-card" style="flex: auto">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">菜式偏好</span>
                    <el-link class="more">更多</el-link>
                </el-row>
                <TableSimple class="card-content" :tableData="menuHabitTable" height="35vh"/>
            </el-card>
            <el-card v-if="false" class="box-card" style="flex: auto">
                <el-row type="flex" justify="space-between" align="middle" slot="header">
                    <span class="title">APP使用日常</span>
                    <el-link class="more">更多</el-link>
                </el-row>
                <TableSimple class="card-content" :tableData="menuHabitTable" height="35vh"/>
            </el-card>
        </el-row>
    </div>
</template>

<script>
import _ from 'lodash'
import moment from 'moment'
import { numCommaFormat } from '@/utils/formatter'
import ChartStageTrend from './chart-stage-trend'
import RegionDistribution from './region-distribution'
import GenderRatio from './gender-ratio'
import AgeRatio from './age-ratio'
import UserRetentionAnalysis from './user-retention-analysis'
import ActivePeriod from './active-period'
import TableSimple from './table-simple'
import { commonMixin } from '@/mixins/user-data'
import { getCategory, getSN8List, getProvinceList, getCityListByProvince } from '@/utils/getSeletorData'
import { dateFormat, dateFormatMonent } from '@/utils/consts'
import debounce from 'lodash/debounce'

export default {
  name: 'UserData',
  mixins: [commonMixin],
  filters: {
    numCommaFormat
  },
  components: {
    TableSimple,
    ActivePeriod,
    UserRetentionAnalysis,
    AgeRatio,
    GenderRatio,
    RegionDistribution,
    ChartStageTrend
  },
  data () {
    return {
      dateFormat,
      options: {
        category: getCategory(),
        model: [],
        province: [],
        city: []
      },
      dateOptions: [
        {
          label: '当天',
          value: '1'
        },
        {
          label: '近7天',
          value: '7'
        },
        {
          label: '近30天',
          value: '30'
        },
        {
          label: '自定义',
          value: 'custom'
        }
      ],
      dateRange: '7',
      queryParameter: {
        category: '',
        model: '',
        province: '',
        city: '',
        dateRange: [moment().add('-7', 'days').format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
      },
      userSurveyData: [
        {
          num: 0,
          label: '新安装设备',
          trend: 0
        }, {
          num: 0,
          label: '新增用户',
          trend: 0
        }, {
          num: 0,
          label: '存储用户',
          trend: 0
        }, {
          num: 0,
          label: '活跃用户',
          trend: 0
        }, {
          num: 0,
          label: '沉默用户',
          trend: 0
        }, {
          num: 0,
          label: '流失用户',
          trend: 0
        }
      ],
      surveyDateRange: '1',
      userStageTrendCheckedType: 'day',
      retentionDateRange: '1',
      loadingOverView: true,
      loadingTableTasteHabit: true,
      loadingTableMenuHabit: true,
      tasteHabitTable: {
        column: [
          {
            label: '口味',
            prop: 'flavor',
            minWidth: '2'
          },
          {
            label: '筛选量',
            prop: 'Selection_times',
            minWidth: '1'
          },
          {
            label: '比列',
            prop: 'Percent',
            minWidth: '3'
          }
        ],
        data: []
      },
      menuHabitTable: {
        column: [
          {
            label: '菜式',
            prop: 'menuName',
            minWidth: '2'
          },
          {
            label: '筛选量',
            prop: 'Selection_times',
            minWidth: '1'
          },
          {
            label: '比列',
            prop: 'Percent',
            minWidth: '3'
          }
        ],
        data: []
      },
      debounceGetData: debounce(this.getData || (() => {
      }), 1000, { leading: true })
    }
  },
  created () {
    this.init()
  },
  computed: {
    showDateRangePicker () {
      return this.dateRange === _.last(this.dateOptions).value
    }
  },
  watch: {
    queryParameter: {
      handler () {
        this.debounceGetData()
      },
      deep: true
    }
  },
  methods: {
    init () {
      this._getSN8List()
      this._getProvinceList()
      this.getData()
    },
    getData () {
      if (this.dateRange !== 'custom' || this.queryParameter.dateRange !== null) {
        this.setQueryParams()
        Promise.all([this._getUserOverview(), this._getUserMenuHabit(), this._getUserTasteHabit()])
      }
    },
    setQueryParams () {
      const { category, model, province, city, dateRange } = this.queryParameter
      this.params = {
        province_name: province,
        city_name: city,
        apptype: category,
        sn8: model,
        start_day: (dateRange && dateRange[0]) || undefined,
        end_day: (dateRange && dateRange[1]) || undefined
      }
    },
    async _getSN8List () {
      this.options.model = await getSN8List.call(this)
    },
    async _getProvinceList () {
      this.options.province = await getProvinceList.call(this)
    },
    async _getCityListByProvince () {
      this.options.city = await getCityListByProvince.call(this)
    },
    async _getUserOverview () {
      this.loadingOverView = true
      const { data: { data, code } } = await this.$http
        .get(this.getApiUrl('dataanalysis_iot/user/getUserOverview', false),
          {
            params: this.params
          })
      this.loadingOverView = false
      if (code === 0) {
        const findIndex = (val) => _.findIndex(this.userSurveyData, ({ label }) => label === val)
        for (let key of Object.keys(data)) {
          switch (key) {
            case 'num_of_active_user':
              this.userSurveyData[findIndex('活跃用户')].num = data[key]
              break
            case 'num_of_loss_user':
              this.userSurveyData[findIndex('流失用户')].num = data[key]
              break
            case 'num_of_new_user':
              this.userSurveyData[findIndex('新增用户')].num = data[key]
              break
            case 'num_of_regist_device':
              this.userSurveyData[findIndex('新安装设备')].num = data[key]
              break
            case 'num_of_retention_user':
              this.userSurveyData[findIndex('存储用户')].num = data[key]
              break
            case 'num_of_silent_user':
              this.userSurveyData[findIndex('沉默用户')].num = data[key]
              break
          }
        }
      }
    },
    async _getUserMenuHabit () {
      this.loadingTableMenuHabit = true
      const { data: { data: { favoriteRecipe }, code } } = await this.$http
        .get(this.getApiUrl('dataanalysis_iot/user/getUserMenuHabit', false),
          {
            params: this.params
          })
      this.loadingTableMenuHabit = false
      if (code === 0) {
        this.menuHabitTable.data = favoriteRecipe
      }
    },
    async _getUserTasteHabit () {
      this.loadingTableTasteHabit = true
      const { data: { data: { favoriteFlavor }, code } } = await this.$http
        .get(this.getApiUrl('dataanalysis_iot/user/getUserTasteHabit', false),
          {
            params: this.params
          })
      this.loadingTableTasteHabit = false
      if (code === 0) {
        this.tasteHabitTable.data = favoriteFlavor
      }
    },
    handleDateChange () {
      switch (this.dateRange) {
        case '':
          this.queryParameter.dateRange = null
          break
        case '1':
          this.queryParameter.dateRange = [moment(new Date()).format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        case '7':
          this.queryParameter.dateRange = [moment().add('-7', 'days').format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        case '30':
          this.queryParameter.dateRange = [moment().add('-30', 'days').format(dateFormatMonent), moment(new Date()).format(dateFormatMonent)]
          break
        case 'custom':
          this.queryParameter.dateRange = null
          break
        default:
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
    @import "~element-theme-chalk/src/common/var.scss";
    @import "@/assets/scss/modules/variables-module.scss";
    @import "@/assets/scss/modules/common-module.scss";

    .page-container {

        .user-data_row {
            & ~ .user-data_row {
                margin-top: $gap-big;
            }

            .box-card {
                & + .box-card {
                    margin-top: 0;
                    margin-left: $gap-default;
                }

                .title {
                    font-weight: bolder;
                    font-size: 145%;
                }

                .mui-radio-group {
                    @include mui-radio-group();
                }

                .el-link.more {
                    color: $--color-primary-light-1;
                }
            }
        }

        .user-data_row--filter {
            @include filter-row;
        }

        .user-data_row--survey {
            .box-card {
                .card-content {
                    .data-item {
                        flex: auto;

                        &:not(:last-of-type) {
                            padding-right: 30px;
                        }

                        & ~ .data-item {
                            padding-left: 30px;
                            border-left: 1px solid $--border-color-base;
                        }

                        .item-row {
                            & ~ .item-row {
                                margin-top: $gap-small;
                            }
                        }

                        .num {
                            font-size: 150%;
                            font-weight: bolder;
                            color: $--color-primary;
                        }

                        .label {
                            font-size: 95%;
                            color: $--color-info;
                        }

                        .trend {
                            font-weight: bold;

                            .range {
                                font-weight: normal;
                                color: $--color-primary-light-1;
                            }
                        }
                    }
                }
            }
        }

        .user-data_row--ratio {
            .box-card {
                flex: 1 1 50%;
            }
        }

        .user-data_row--retention {
            .index-btn-group {
                ::v-deep {
                    .label {
                        @include style__grey;
                    }

                    .el-date-editor {
                        @include el-date-editor__grey;
                    }
                }
            }
        }
    }
</style>
